<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Swoole\Process;

class Entrypoint extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:entrypoint';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * @var bool
     */
    private $running = true;

    private $process;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        pcntl_async_signals(true);
        // 安装信号量 回调函数
        pcntl_signal(SIGTERM, [$this, 'stopSignal']);
        pcntl_signal(SIGQUIT, [$this, 'stopSignal']);
        pcntl_signal(SIGINT, [$this, 'stopSignal']);
        $this->process = config('entrypoint');
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->start();
    }

    /**
     * @return void
     */
    public function start()
    {
        while ($this->running) {
            foreach ($this->process as $process => $config) {
                $this->check($process, $config);
            }
            sleep(1);
        }

        $this->stop();
    }

    public function stop()
    {
        foreach ($this->process as $process => $config) {
            echo "发送停止信号{$process}\n";
            $p = new Process(function () use ($config) {
                exec($config['stop']);
            });
            $p->start();
        }
    }

    /**
     * 检测进程
     * @param $process
     * @param $config
     * @return void
     */
    public function check($process, $config)
    {
        if ($this->pid($config['ps']) == 0) {
            echo "检测不到{$process}这个进程，重新拉起" . PHP_EOL;
            $p = new Process(function () use($config) {
                exec($config['start']);
            });
            $p->start();
        }
    }

    /**
     * @return void
     */
    public function stopSignal($signo)
    {
        echo "stopSignal" . $signo . PHP_EOL;
        $this->running = false;
    }

    /**
     * 获取pid
     * @param array $ps
     * @return int
     */
    private function pid(array $ps): int
    {
        $args = [];
        foreach ($ps as $p) {
            // shell 元字符转义
            $args[] = 'grep ' . escapeshellcmd($p);
        }
        $cmd = 'ps -ef | ' . implode(' | ', $args) . ' | grep -v "grep" | awk \'{print $2}\'';
        echo $cmd . PHP_EOL;
        return (int)exec($cmd);
    }
}
